//
//  CheckInViewController.m
//  CS Inventory Manager
//
//  Created by Ian Smith on 4/5/13.
//  Copyright (c) 2013 Transylvania University. All rights reserved.
//

#import "CheckInViewController.h"

@interface CheckInViewController ()

@end

@implementation CheckInViewController
@synthesize navBar, notes, details, late, balance, item;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

-(void)cancelButton:(id)sender {
    [self.presentingViewController dismissViewControllerAnimated:YES completion:NULL];
}

-(void)doneButton:(id)sender {
    //Upload the check-in to database here
    NSString *urlStr = [NSString stringWithFormat:@"http://www.cs.transy.edu/zoellers/inventory/checkin.php?secret=pass&coid=%d&notes=%@&charge=%@", item.checkoutActive.checkoutID, notes.text, balance.text];
    NSString *final = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    NSLog(@"The url is: >>>>>%@<<<<<", final);
    
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:final]];
    
    // make web request and catch error
    NSError * e;
    NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&e];
    
    // log the value returned from the web server
    NSString *value = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSLog(@"return from web: %@", value);
    
    [self.presentingViewController viewWillAppear:NO];
    [self.presentingViewController dismissViewControllerAnimated:YES completion:NULL];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor grayColor];
    NSMutableString *detailString = [[NSMutableString alloc] initWithString:item.model];
    [detailString appendString:@" checked out to "];
    if ([[[item checkoutActive] patrons] count] == 1) {
        // single patron
        [detailString appendString:[[[[item checkoutActive] patrons] objectAtIndex:0] name]];
    } else {
        // multiple patrons
        [detailString appendString:@"Multiple Patrons"];
    }

    details.text = detailString;
    notes.text = NULL;
	//Check to see if Item is late
    if ([item.checkoutActive.dueDate timeIntervalSinceNow] > 0) {
        //Item is not late
        late.text = NULL;
    } else {
        late.text = @"This Item is late.";
    }
    balance.keyboardType = UIKeyboardTypeNumberPad;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
